#include "RCU.h"
void SystemClockInit(void)
{
    /*
    1.使能HSE   
    2.等待HSERDY标志位置1
    3.设置FLASH指令等待周期
    4.使能指令预取
    5.设置锁相环的N,M,R参数 M=1 N=16 R=3
    6.系统时钟源切为PLLR
    7.读取状态直至切换完成
    */
    //1.使能HSE
    RCC->CR |= 0x00010000;
    //2.等待HSERDY标志位置1
    while( !((RCC->CR) & (0x00020000)) );
    //3.设置FLASH指令等待周期
    U32SetBitField(FLASH->ACR,0,2,2);
    //4.使能指令预取
    FLASH->ACR |= 0x00000100;
    //5.配置锁相环
    /*
    1. Disable the PLL by setting PLLON to 0 in Clock control register (RCC_CR).
    2. Wait until PLLRDY is cleared. The PLL is now fully stopped.
    3. Change the desired parameter.
    4. Enable the PLL again by setting PLLON to 1.
    5. Enable the desired PLL outputs by configuring PLLPEN, PLLQEN, and PLLREN in PLL 
    configuration register (RCC_PLLCFGR)
    */
    RCC->CR &=~ (uint32_t)(1<<24);
    while( 0 != ((RCC->CR) & (1<<25)) );
    U32SetBitField(RCC->PLLCFGR,0,1,3);//PLLRC = 0b11(HSE)    
    U32SetBitField(RCC->PLLCFGR,4,6,0);//M=1
    U32SetBitField(RCC->PLLCFGR,8,14,16);//N=16
    U32SetBitField(RCC->PLLCFGR,29,31,2);//R=3
    U32SetBitField(RCC->PLLCFGR,25,27,1);//Q=2    
    RCC->CR |= (1<<24);
    RCC->PLLCFGR |= (1<<28);
    //6.系统时钟源切为PLLR
    U32SetBitField(RCC->CFGR,0,2,2);
    //7.读取状态直至切换完成
    while(2 != GET_BITS(RCC->CFGR,3,5));

    #if RCU_MCO_MODE==1
    /*
    1.开启MCO功能
    2.选择时钟源为系统时钟
    3.配置分频系数为2
    */
    RCC->CFGR &= 0x00FFFFFF;//MCOSEL[3:0] = 0b0000 MCOPRE[3:0] = 0b0000
    RCC->CFGR |= 0x61000000;//MCOSEL[3:0] = 0b0001 MCOPRE[3:0] = 0b0001
    #endif
}
